<template>
    <view>
        <!-- pages/activity_post/activity_post.wxml -->
        <view class="weui-toptips weui-toptips_warn" v-if="showTopTips">{{ errorInfo }}</view>
        <view class="container">
            <form @submit.stop.prevent="formSubmit">
                <view class="section1">
                    <input class="easyInput" name="subject" :value="subject" placeholder="标题（最多只能输入80个字符）" />

                    <textarea v-if="!fullScreen" class="weui-input detailText" name="message" placeholder="活动详情 请输入活动内容的详细描述" :value="message" maxlength="-1" />
                    <view class="weui-cell" @tap="chooseImage">
                        <view class="weui-cell__hd">
                            <view class="weui-label">头图</view>
                            <view class="att-tip">(大小不超过4M)</view>
                        </view>
                        <view class="weui-cell__bd"></view>
                        <view class="weui-cell__ft weui-cell__ft_in-access">
                            <view class="img_box">
                                <image class="logo" mode="aspectFill" :src="imageList[0] ? imageList[0].src : minImgDoc + 'post_course_image.png'"></image>
                            </view>
                        </view>
                    </view>
                </view>

                <view class="section1">
                    <view class=".activity-type-c">
                        <view class="time-tip activity-tip">类型</view>
                        <input name="activitytype" :value="activitytype" placeholder="请输入活动类型" :focus="isSelf" />
                        <picker class="dateType" mode="selector" :value="activityIndex" :range="activitytypelist" @change="activityTypeChange">
                            <text :decode="true">{{ activitytypelist[activityIndex] ? activitytypelist[activityIndex] : '自定义' }}</text>
                        </picker>
                    </view>
                </view>

                <view class="section1">
                    <view class="teachTime">
                        <view class="tt_title">报名时间</view>
                        <view class="tt_pickercontent">
                            <picker class="dateType" mode="date" :value="enrolStart" @change="bindEnrolStartChange">
                                <text>{{ enrolStart ? enrolStart : '请选择' }}</text>
                            </picker>
                            <view class="zhi">至</view>
                            <picker class="dateType" mode="date" :value="enrolEnd" :start="enrolStart" @change="bindEnrolEndChange">
                                <text :decode="true">{{ enrolEnd ? enrolEnd : '请选择' }}</text>
                            </picker>
                        </view>
                    </view>
                </view>

                <view class="section1">
                    <view class="teachTime">
                        <view class="tt_title">活动时间</view>
                        <view class="tt_pickercontent">
                            <view class="time-tip">开始时间</view>
                            <picker class="dateType" mode="date" :value="activityDateStart" @change="activityDateStartChange">
                                <text>{{ activityDateStart ? activityDateStart : '请选择' }}</text>
                            </picker>
                            <picker class="dateType" mode="time" :value="activityTimeStart" :start="activityTimeStart" @change="activityTimeStartChange">
                                <text :decode="true">{{ activityTimeStart ? activityTimeStart : '00:00' }}</text>
                            </picker>
                        </view>
                        <view class="tt_pickercontent">
                            <view class="time-tip">结束时间</view>
                            <picker class="dateType" mode="date" :value="activityDateEnd" @change="activityDateEndChange">
                                <text>{{ activityDateEnd ? activityDateEnd : '请选择' }}</text>
                            </picker>
                            <picker class="dateType" mode="time" :value="activityTimeEnd" :start="activityTimeEnd" @change="activityTimeEndChange">
                                <text :decode="true">{{ activityTimeEnd ? activityTimeEnd : '00:00' }}</text>
                            </picker>
                        </view>
                    </view>

                    <view class="weui-cell">
                        <view class="weui-cell__bd">活动地点</view>
                        <input class="weui-cell__ft weui-cell__ft_in-access" name="activityplace" :value="activityplace" />
                    </view>
                    <view class="weui-cell">
                        <view class="weui-cell__bd">活动人数</view>
                        <input type="number" class="weui-cell__ft weui-cell__ft_in-access" name="activitynumber" :value="activitynumber" />
                    </view>
                    <picker mode="selector" :value="genderIndex" :range="genderlist" @change="bindGenderChange">
                        <view class="weui-cell picker-cell">
                            <view class="weui-cell__bd">性别</view>
                            <view class="weui-cell__ft weui-cell__ft_in-access">
                                {{ genderlist[genderIndex] ? genderlist[genderIndex] : '' }}
                            </view>
                        </view>
                    </picker>
                </view>

                <view class="section1">
                    <view class="weui-cell">
                        <view class="weui-cell__bd">消耗积分</view>
                        <input type="number" class="weui-cell__ft weui-cell__ft_in-access" name="activitycredit" :value="activitycredit" />
                    </view>
                    <view class="weui-cell">
                        <view class="weui-cell__bd">每人花销</view>
                        <input type="digit" class="weui-cell__ft weui-cell__ft_in-access" name="cost" :value="cost" />
                    </view>
                </view>

                <button class="postBtn" :disabled="postLock" type="primary" formType="submit">发布</button>
            </form>
        </view>
    </view>
</template>

<script>
// pages/activity_post/activity_post.js
const postInfoUrl = require('../../config').postInfoUrl;

const uploadFileUrl = require('../../config').uploadFileUrl;

const postThreadUrl = require('../../config').postThreadUrl;

const util = require('../../utils/util.js');

const datacheck = require('../../utils/datacheck.js');

const minImgDoc = require('../../config').minImgDoc;


const app = getApp(); // 附件分类

var fileCatalog = {
    image: 0,
    audio: 1,
    video: 2
};
export default {
    data() {
        return {
            minImgDoc: minImgDoc,
            imageList: [],
            genderlist: ['不限', '男', '女'],
            genderIndex: 0,
            postLock: false,
            activitytypelist: [],
            activityIndex: -1,
            fid: '',
            uploadhash: '',
            classTypeList: '',
            typeObj: '',
            enrolStart: '',
            enrolEnd: '',
            activityDateStart: '',
            activityTimeStart: '',
            activityDateEnd: '',
            activityTimeEnd: '',
            isSelf: false,
            activitytype: '',
            errorInfo: '',
            showTopTips: false,
            subject: '',
            fullScreen: '',
            message: '',
            activityplace: '',
            activitynumber: 0,
            activitycredit: '',
            cost: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {


        if (options.fid) {
            this.fid= options.fid;
        }

        let pages = getCurrentPages(); //获取当前页面

        let prevPage = pages[pages.length - 2]; //获取上个页面

        if (prevPage.$data.dataDic.Variables.activity_setting.activitytype) {
            let activitytypelist = prevPage.$data.dataDic.Variables.activity_setting.activitytype;
            activitytypelist.push('自定义');
            this.activitytypelist= activitytypelist;
        }

        this.checkPost();
    },
    methods: {
        checkPost() {
            var data = {
                fid: this.fid
            };
            var url = postInfoUrl + '&submodule=checkpost&version=5';
            app.globalData.apimanager
                .getRequest(url, data)
                .then((res) => {
                    if (res.Variables.allowperm) {
                        this.uploadhash= res.Variables.allowperm.uploadhash;
                    }

                    var types = res.Variables.threadtypes.types;
                    var array = [];

                    for (let key in types) {
                        let value = types[key];
                        let data = {
                            typeid: key,
                            name: value
                        };
                        array.push(data);
                    }

                    this.classTypeList= array;this.typeObj= res.Variables.threadtypes.types;
                })
                .catch((res) => {}); // app.apimanager.getRequest(postActivity, data).then(res => {
            //   if (res.Variables.activitytypelist) {
            //     var activitytypelist = res.Variables.activitytypelist
            //     activitytypelist.push('自定义')
            //     this.//       activitytypelist= res.Variables.activitytypelist
            //   }
            // }).catch(res => {})
        },

        chooseImage(e) {
            var index = e.currentTarget.id;
            uni.chooseImage({
                count: 1,

                success(res) {
                    for (let key in res.tempFilePaths) {
                        let imageSrc = res.tempFilePaths[key];
                        this.uploadFile(imageSrc, fileCatalog.image, index);
                    }
                }
            });
        },

        uploadFile(uploadSrc, type) {
            var uploadUrl = uploadFileUrl + '&fid=' + this.fid;
            let uploadhash = this.uploadhash;
            let uid = app.globalData.uid;
            let postDic = {
                hash: uploadhash,
                uid: uid
            };
            uni.showLoading({
                title: '上传附件',
                icon: 'loading'
            });
            app.globalData.apimanager
                .uploadFile(uploadUrl, uploadSrc, 'Filedata', postDic)
                .then((res) => {
                    uni.hideLoading();
                    var result = datacheck.uploadStatusCheck(res);

                    if (result.success) {
                        uni.showToast({
                            title: '上传成功',
                            icon: 'success',
                            duration: app.globalData.duration
                        });
                        let aid = result.data;

                        if (type == fileCatalog.image) {
                            var imageList = [];
                            let imgObj = {
                                aid: aid,
                                src: uploadSrc
                            };
                            imageList.push(imgObj);
                            this.imageList= imageList;
                        }
                    } else {
                        uni.showModal({
                            content: result.data,
                            showCancel: false,
                            confirmText: '确定'
                        });
                    }
                })
                .catch((res) => {
                    uni.hideLoading();
                    console.log(res);
                    uni.showModal({
                        content: '上传失败',
                        showCancel: false,
                        confirmText: '确定'
                    });
                });
        },

        bindEnrolStartChange(e) {
            this.enrolStart= e.detail.value;
        },

        bindEnrolEndChange(e) {
            this.enrolEnd= e.detail.value;
        },

        activityDateStartChange(e) {
            this.activityDateStart= e.detail.value;
        },

        activityTimeStartChange(e) {
            this.activityTimeStart= e.detail.value;
        },

        activityDateEndChange(e) {
            this.activityDateEnd= e.detail.value;
        },

        activityTimeEndChange(e) {
            this.activityTimeEnd= e.detail.value;
        },

        bindGenderChange(e) {
            this.genderIndex= e.detail.value;
        },

        activityTypeChange(e) {
            var activityIndex = e.detail.value;
            this.activityIndex= e.detail.value;

            if (activityIndex == this.activitytypelist.length - 1) {
                this.isSelf= true;this.activitytype= '';
            } else {
                this.activitytype= this.activitytypelist[activityIndex];
            }
        },

        formSubmit(e) {
            var errorInfo = '';
            var ifError = true;

            if (!e.detail.value.subject) {
                errorInfo = '请输入标题';
            } else {
                if (datacheck.isEmojiCharacter(e.detail.value.message) || datacheck.isEmojiCharacter(e.detail.value.subject)) {
                    errorInfo = '不能使用emoji表情';
                } else {
                    if (!e.detail.value.activitytype) {
                        errorInfo = '选择活动类型';
                    } else {
                        if (!this.activityDateStart) {
                            errorInfo = '选择活动开始时间';
                        } else {
                            if (!this.activityDateStart) {
                                errorInfo = '选择活动结束时间';
                            } else {
                                if (!e.detail.value.activityplace) {
                                    errorInfo = '选择活动地点';
                                } else {
                                    ifError = false;
                                }
                            }
                        }
                    }
                }
            }

            if (ifError) {
                this.errorInfo= errorInfo;this.showTopTips= true;
                setTimeout(function () {
                    this.showTopTips= false;
                }, 2000);
                return;
            }

            var startTime = this.activityDateStart + ' ' + this.activityTimeStart;
            var endTime = this.activityDateEnd + ' ' + this.activityTimeEnd;
            var postData = {
                special: 4,
                formhash: app.globalData.formhash,
                allownoticeauthor: 1,
                subject: e.detail.value.subject,
                message: util.filterEmoji(e.detail.value.message),
                activitytime: 1,
                activityclass: e.detail.value.activitytype,
                'starttimefrom[1]': startTime,
                starttimeto: endTime,
                activityplace: e.detail.value.activityplace,
                activitynumber: e.detail.value.activitynumber,
                gender: this.genderIndex,
                activitycredit: e.detail.value.activitycredit,
                cost: e.detail.value.cost,
                activitystarttime: this.enrolStart,
                activityexpiration: this.enrolEnd,
                topicsubmit: 'yes'
            };

            if (this.imageList.length > 0) {
                for (let i = 0; i < this.imageList.length; i++) {
                    let imgObj = this.imageList[i];
                    let aid = imgObj['aid'];
                    let attachKey = 'attachnew[' + aid + '][description]';
                    postData[attachKey] = '';
                }
            }

            let requestUrl = postThreadUrl + '&fid=' + this.fid;
            uni.showLoading({
                title: '发布中...',
                icon: 'loading'
            });
            this.postLock= true;
            app.globalData.apimanager
                .postRequest(requestUrl, postData)
                .then((res) => {
                    uni.hideLoading();
                    this.postLock= false;

                    if (res.Message.messageval.indexOf('succeed') != -1) {
                        var pages = getCurrentPages();
                        var prevPage = pages[pages.length - 2]; //上一个页面

                        prevPage.refreshRequest();
                        uni.navigateBack({});
                    }

                    uni.showToast({
                        title: res.Message.messagestr,
                        icon: 'none'
                    });
                })
                .catch((res) => {
                    console.log(res);
                    this.postLock= false;
                    uni.hideLoading();
                });
        }
    }
};
</script>
<style>
@import './activity_post.css';
</style>
